package com.kedou.net;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.kedou.app.Config;
import com.kedou.app.R;
import com.kedou.application.Myapplication;
import com.kedou.util.DebugUtil;
import com.kedou.util.DensityUtil;
import com.kedou.util.Util;

/**
 * 后台请求：APP刚启动时获取信息，主要为配置信息
 * 
 * @author zhouchao
 * 
 */
public class PostUpdateInfo {

	public PostUpdateInfo(String serial, String resolution, String os,
			String deviceId, String version,
			final SuccessCallback successCallback,
			final FailCallback failCallback, final Context context) {
		new NetConnection(
				Util.getSDBaseUrl() + Config.URL_UPDATEINFO,
				HttpMethod.POST,
				new NetConnection.SuccessCallback() {

					@Override
					public void onSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							switch (obj.getInt(Config.KEY_STATUSCODE)) {
							case Config.RESULT_STATUS_SUCCESS:
								JSONObject jsonObject = obj
										.getJSONObject(Config.KEY_DATA);
								String mSerial = "";
								String mBaseUrl = "";
								String mSlogan = "";
								if (jsonObject.has(Config.KEY_SERIAL)) {
									mSerial = jsonObject
											.getString(Config.KEY_SERIAL);
								}
								if (jsonObject.has(Config.KEY_BASEURL)) {
									mBaseUrl = jsonObject
											.getString(Config.KEY_BASEURL);
								}
								if (jsonObject.has(Config.KEY_SLOGAN)) {
									mSlogan = jsonObject
											.getString(Config.KEY_SLOGAN);
								}
								if (successCallback != null) {
									successCallback.onSuccess(
											obj.getString(Config.KEY_STATUSMSG),
											mBaseUrl, mSlogan, mSerial);
								}
								break;

							default:
								if (failCallback != null) {
									failCallback.onFail(obj
											.getString(Config.KEY_STATUSMSG));
								}
								break;
							}
						} catch (JSONException e) {
							e.printStackTrace();
							if (failCallback != null) {
								failCallback.onFail(context.getResources()
										.getString(R.string.server_have_wrong));
							}
						}
					}
				}, new NetConnection.FailCallback() {

					@Override
					public void onFail() {
						if (failCallback != null) {
							failCallback.onFail(context.getResources()
									.getString(R.string.server_have_wrong));
						}
					}
				}, Config.KEY_VERSION, Util.getAppVersionName(context),
				Config.KEY_SERIAL, Util.getSDSerial(), Config.KEY_RESOLUTION,
				DensityUtil.getResolution(context), Config.KEY_OS,
				Config.SOURCE, Config.KEY_DEVICE, Util.getImei(context));
	}

	public static interface SuccessCallback {
		void onSuccess(String msg, String baseurl, String slogan, String serial);
	}

	public static interface FailCallback {
		void onFail(String msg);
	}
}
